package com.bsoft.rpc.basic.dynamicProxy.cglib;

import com.bsoft.rpc.basic.dynamicProxy.NetTransport;
import com.bsoft.rpc.basic.dynamicProxy.RpcRequest;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 通过cglib来实现rpc远程调用接口的过程
 */
public class CGlibProxyHandler implements MethodInterceptor {
    /**
     * 被代理的类型
     */
    private Class<?> clazz;
    /**
     * 远程地址
     */
    private String address;
    /**
     * 远程端口
     */
    private int port;

    public CGlibProxyHandler(Class<?> clazz, String address, int port) {
        this.clazz = clazz;
        this.address = address;
        this.port = port;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        // 实现远程消息组装，通信和返回数据组装逻辑
        RpcRequest request = new RpcRequest();
        // 接口名
        request.setServiceName(clazz.getName());
        // 方法名
        request.setMethodName(method.getName());
        // 入参类型
        request.setParamsType(method.getParameterTypes());
        // 入参内容
        request.setParams(objects);
        // 远程通信地址
        request.setAddress(address);
        request.setPort(port);

        // 进行远程通信，连接到服务端
        return NetTransport.sendRequest(request, method.getReturnType());
    }
}
